import json
from pathlib import Path

class VocabularyAPI:
    """英语词汇查询本地接口（JSON格式支持）"""
    
    def __init__(self, merged_file_path):
        """
        初始化词汇查询接口
        Args:
            merged_file_path: 合并词汇表JSON文件路径
        """
        self.merged_file_path = Path(merged_file_path)
        self.vocab_dict = {}
        self.category_index = {}
        self.is_loaded = False
        self.total_words = 0
        
    def initialize(self):
        """
        初始化加载词汇数据（支持JSON格式）
        
        Returns:
            bool: 加载成功返回True，失败返回False
        """
        try:
            # 读取JSON词汇表文件
            with open(self.merged_file_path, 'r', encoding='utf-8') as f:
                vocab_list = json.load(f)
            
            # 清空现有数据
            self.vocab_dict.clear()
            self.category_index.clear()
            
            # 解析数据
            valid_count = 0
            for index, word_info in enumerate(vocab_list):
                if 'word' in word_info and word_info['word'].strip():
                    word_key = word_info['word'].strip().lower()
                    
                    # 构建标准化单词信息
                    standardized_info = {
                        'raw_word': word_info['word'].strip(),
                        'uk_phone': word_info.get('ukphone', '').strip(),
                        'us_phone': word_info.get('usphone', '').strip(),
                        'definition': word_info.get('translations', '').strip(),
                        'category': word_info.get('category', '未知').strip(),
                        'row_index': index
                    }
                    
                    # 更新分类索引
                    category = standardized_info['category']
                    if category not in self.category_index:
                        self.category_index[category] = []
                    self.category_index[category].append(word_key)
                    
                    # 添加到主字典
                    self.vocab_dict[word_key] = standardized_info
                    valid_count += 1
            
            self.total_words = valid_count
            self.is_loaded = True
    
            self._print_category_stats()
            return True
            
        except Exception as e:
            print(f"❌ 词汇表初始化失败: {e}")
            return False
    
    def _print_category_stats(self):
        """打印分类统计信息"""
        print("📊 词汇表加载完成，分类统计:")
        for category, words in self.category_index.items():
            print(f"   {category}: {len(words)} 个单词")
        print(f"   总计: {self.total_words} 个单词")
    
    def query_word(self, word):
        """
        查询单词接口
        
        Args:
            word (str): 要查询的单词
            
        Returns:
            dict: 查询结果
        """
        if not self.is_loaded:
            return {
                'success': False,
                'word': word,
                'exists': False,
                'data': None,
                'error': '词汇表未初始化，请先调用initialize()方法'
            }
        
        try:
            word_key = word.strip().lower()
            
            if word_key in self.vocab_dict:
                word_data = self.vocab_dict[word_key].copy()
                
                return {
                    'success': True,
                    'word': word,
                    'exists': True,
                    'data': word_data,
                    'error': None
                }
            else:
                return {
                    'success': True,
                    'word': word,
                    'exists': False,
                    'data': None,
                    'error': None
                }
                
        except Exception as e:
            return {
                'success': False,
                'word': word,
                'exists': False,
                'data': None,
                'error': f'查询过程中出错: {str(e)}'
            }
        
